﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kavaa.Modules.PortailMedical.Entity;
using Kavaa.Modules.PortailMedical.Presentation.Models;
using Kavaa.Modules.PortailMedical.Interface;
using System.IO;
using Kavaa.Modules.PortailMedical.Presentation.serviceJava;

namespace Kavaa.Modules.PortailMedical.Presentation.Controllers
{
    public class CabinetController : Controller
    {
        public static int SelectedClinique1;
        public static int SelectedActe1;
        public static List<Utilisateur> utilisateurs = new List<Utilisateur>();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AccueilCabinet()
        {
            return View();
        }
      
        public ActionResult Accreditation()
        {
            return View();
        }

        public ActionResult Message()
        {
            if (Session["user"] != null)
            {
                Utilisateur user = (Utilisateur)(Session["user"]);
                Utilisateurs users = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetUtilisateurs(user.Acteur.Id);
                return PartialView(users);
            }
            else
            {
                RedirectToAction("SignIn", "test");
            }
            return PartialView();
        }

        public ActionResult Demande()
        {
            List<Specialite> Specialites = new List<Specialite>();
            Specialites = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetSpecialites();
            ViewBag.specialites = Specialites;
            Nomenclatures nomenclatures = new Nomenclatures();
            nomenclatures = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetNomenclatures();
            ViewBag.nomenclatures = nomenclatures;

            Actes actes = new Actes();
            actes = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetActes();
            ViewBag.actes = actes;

            Villes villes = new Villes();
            villes = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetVilles();
            ViewBag.villes = villes;
            return PartialView();

        }

        public ActionResult ComptesCabinet()
        {
            if (Session["user"] != null)
            {
                Utilisateur user = (Utilisateur)(Session["user"]);
                Utilisateurs users = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetUtilisateurs(user.Acteur.Id);
                foreach (Utilisateur userr in users)
                {
                    if (userr.Etatcompte == 0)
                    {
                        userr.Etat = "Désactivé";
                    }
                    else if (userr.Etatcompte == 1)
                    {
                        userr.Etat = "Activé";
                    }
                }
                return PartialView(users);
            }
            else
            {
                RedirectToAction("SignIn", "test");
            }
            return View();
        }
        public ActionResult CreerUser()
        {
            ViewBag.list = tModel.getListCabinet();
            return View();
        }

        [HttpPost]
        public ActionResult CreerUser(MyViewModel model)
        {
            Utilisateur userConnecte = (Utilisateur)(Session["user"]);

            int id = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.AddUtilisateur(model.utilisateur, userConnecte.Acteur.Id);
           
            Utilisateur user = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetUserById(id);

            string emailFrom = userConnecte.Email;
            string password = userConnecte.PasswordMail;
            string emailTo = user.Email;
            string fileAttachmentPath = @"C:\temp\itil.txt";
            int result = -1;


            try
            {
                IMail client = new Kavaa.Modules.PortailMedical.Services.Mail();

                List<FileAttachment> allAttachments = new List<FileAttachment>();
                FileAttachment attachment = new FileAttachment();
                attachment.Info = new FileInfo(fileAttachmentPath);
                attachment.FileContentBase64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(fileAttachmentPath));
                allAttachments.Add(attachment);

                result = client.SendEmail(emailFrom, password, new string[] { emailTo }, null,
                  "It works!!!", "Votre login: " + user.login + "_ Votre mot de passe:" + user.motPasse, false, allAttachments.ToArray());
                Console.WriteLine("Result: " + result);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            return RedirectToAction("ComptesCabinet");
        }

        [HttpGet]
        public ActionResult UpdateUser(int idUtilisateur, string nom, string prenom, string fonction, string telephone, string email) 
        {
           // Utilisateur userConnecte = TestController.userlogged;
            Utilisateur userConnecte = (Utilisateur)(Session["user"]);
           
                foreach (Utilisateur user in Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetUtilisateurs(userConnecte.Acteur.Id))
                {
                    if (user.Id == idUtilisateur)
                    {
                        Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.UpdateUtilisateur(idUtilisateur, nom, prenom, fonction, telephone, email);

                    }

                }
                System.Diagnostics.Debug.Write("id=lalalal" + idUtilisateur + "Lalalalalala");

                //Utilisateur userr = (Utilisateur)(Session["user"]);
                //Utilisateurs users = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetUtilisateurs(userr.Acteur.Id);
                //return PartialView(users);
           return RedirectToAction("ComptesCabinet");
        }

        [HttpPost]
        public ActionResult DeleteUtilisateur(int[] selectedusers)
        {

          //  Utilisateur userConnecte = TestController.userlogged;
            Utilisateur userConnecte = (Utilisateur)(Session["user"]);
            foreach (int nameID in selectedusers)
            {
                foreach (Utilisateur user in Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetUtilisateurs(userConnecte.Acteur.Id))
                {
                    if (nameID == user.Id)
                    {
                        Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.DeleteUtilisateur(nameID);

                    }

                }
                System.Diagnostics.Debug.Write("id=lalalal" + nameID + "Lalalalalala");
            }

            return RedirectToAction("ComptesCabinet");
        }

        public ActionResult GetAccreditationsEnCoursByUser()
            {

                Utilisateur userConnecte =(Utilisateur)(Session["user"]);  
                Accreditations AccreditEnCours= Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetAccreditationsEnCoursByUser(userConnecte.Id);
                return PartialView(AccreditEnCours);
            }

        public ActionResult GetAccreditationsAccordeesByUser()
        {

            Utilisateur userConnecte = (Utilisateur)(Session["user"]);
            Accreditations AccreditAccordees = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetAccreditationsAccordeesByUser(userConnecte.Id);
            return PartialView(AccreditAccordees);
        }

        public ActionResult GetAccreditationsRefuseesByUser()
        {
            Utilisateur userConnecte = (Utilisateur)(Session["user"]);
            Accreditations AccreditRefusees = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetAccreditationsRefuseesByUser(userConnecte.Id);
            return PartialView(AccreditRefusees);
        }

        public ActionResult Deconnexion() 
        {
           // TestController.userlogged = null;
            Utilisateur userConnecte = (Utilisateur)(Session["user"]);
            userConnecte = null;
            Session["user"] = null;
            return RedirectToAction("SignIn", "Test");
        }

        [HttpPost]
        public ActionResult Reservation(int selectedClinique, int acteId)
        {
            SelectedClinique1 = selectedClinique;
            SelectedActe1 = acteId;


            System.Diagnostics.Debug.Write("looloololoo:" + selectedClinique);

            Reservations Reservations = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetReservbloquees(selectedClinique, acteId);
            List<Reservation> reservs = new List<Entity.Reservation>();
            reservs = Reservations;
            ViewBag.Reservations = reservs;

            System.Diagnostics.Debug.Write("lalilali" + Reservations.Count);
            foreach (Reservation Reservation in Reservations)
            {
                System.Diagnostics.Debug.Write("DateDebut:" + Reservation.DateDebut + ";DateFin:" + Reservation.DateFin);
                System.Diagnostics.Debug.Write("dateTime" + Reservation.DateDebut.TimeOfDay);
                System.Diagnostics.Debug.Write("date" + Reservation.DateDebut.Date);
            }

            return View();
        }
        [HttpPost]
        public ActionResult GetReservations()
        {
            Reservations Reservations = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetReservbloquees(SelectedClinique1, SelectedActe1);
            System.Diagnostics.Debug.Write("lalilali de getreservs:" + Reservations.Count);

            List<Reservation> reservs = new List<Reservation>();
            reservs = Reservations;
            return Json(reservs.ToArray(), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult GetReservationsMedecin()
        {
            Utilisateur user = (Utilisateur)(Session["user"]);
            Reservations Reservations = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetReservMedecin(user.Id);
            System.Diagnostics.Debug.Write("lalilali de getreservs:" + Reservations.Count);

            List<Reservation> reservs = new List<Reservation>();
            reservs = Reservations;
            return Json(reservs.ToArray(), JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult GetProprietesCategorie(int id_categorie)
        {
            Proprietes proprietes = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetProprietesCategorie(id_categorie);
            List<Propriete> Proprietes2 = new List<Propriete>();
            Proprietes2 = proprietes;
            return Json(Proprietes2.ToArray(), JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult GetReservMedecinEnCours()
        {
            Utilisateur user = (Utilisateur)(Session["user"]);
            Reservations Reservations = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetReservMedecinEnCours(user.Id);
            List<Reservation> reservs = new List<Reservation>();
            reservs = Reservations;
            return Json(reservs.ToArray(), JsonRequestBehavior.AllowGet);
        }
        [HttpPost]

        public ActionResult GetReservMedecinAccordees()
        {
            Utilisateur user = (Utilisateur)(Session["user"]);
            Reservations Reservations = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetReservMedecinAccordees(user.Id);
            List<Reservation> reservs = new List<Reservation>();
            reservs = Reservations;
            return Json(reservs.ToArray(), JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult GetReservMedecinRefusees()
        {
            Utilisateur user = (Utilisateur)(Session["user"]);
            Reservations Reservations = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetReservMedecinRefusees(user.Id);
            List<Reservation> reservs = new List<Reservation>();
            reservs = Reservations;
            return Json(reservs.ToArray(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult AccueilReservation()
        {
            List<Specialite> Specialites = new List<Specialite>();
            Specialites = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetSpecialites();
            ViewBag.specialites = Specialites;
            Nomenclatures nomenclatures = new Nomenclatures();
            nomenclatures = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetNomenclatures();
            ViewBag.nomenclatures = nomenclatures;

            Actes actes = new Actes();
            actes = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetActes();
            ViewBag.actes = actes;




            return View();
        }

        [HttpPost]
        public void SaveReservation(long DateDebut, long DateFin, String body, string bloc, int id)
        {
            Utilisateur user = (Utilisateur)(Session["user"]);
            DateTime origin = new DateTime(1970, 1, 1, 2, 0, 0, 0);
            DateTime DateDebut2 = origin.AddMilliseconds(DateDebut);
            DateTime DateFin2 = origin.AddMilliseconds(DateFin);

            Boolean test = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.existReserv(id);
            if (test == true)
            {
                Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.UpdateReservation(DateDebut2, DateFin2, SelectedActe1, SelectedClinique1, user.Id, body, id);

            }
            else
            {
                int id_reserv = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.SaveReservation(id, DateDebut2, DateFin2, SelectedActe1, SelectedClinique1, user.Id, body);
                Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.AddReservCategorie(id, Convert.ToInt32(bloc));
            }
        }
        [HttpPost]
        public void DeleteReservation(int idreserv)
        {
            Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.DeleteReserv(idreserv);
        }

        [HttpPost]
        public ActionResult IsMedecinFree(long DateDebut, long DateFin)
        {
            Utilisateur user = (Utilisateur)(Session["user"]);
            DateTime origin = new DateTime(1970, 1, 1, 2, 0, 0, 0);
            DateTime DateDebut2 = origin.AddMilliseconds(DateDebut);
            DateTime DateFin2 = origin.AddMilliseconds(DateFin);


            Boolean result = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.IsMedecinFree(DateDebut2, DateFin2, user.Id);
            return Json(new { returnvalue = result });
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult GetBlocsDispo(long DateDebut, long DateFin)
        {
            DateTime origin = new DateTime(1970, 1, 1, 2, 0, 0, 0);
            DateTime DateDebut2 = origin.AddMilliseconds(DateDebut);
            DateTime DateFin2 = origin.AddMilliseconds(DateFin);
            List<Categorie> list = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetBlocsDispo(DateDebut2, DateFin2, SelectedClinique1, SelectedActe1);
            var modelData = list.Select(m => new SelectListItem()
            {
                Text = m.Name,
                Value = m.Id.ToString(),

            });

            return Json(modelData, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public PartialViewResult ListCliniquesAccredit(MyViewModel model)
        {
            Utilisateur user = (Utilisateur)(Session["user"]);
            Cliniques cliniques = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.DecouvrirCliniquesAccredit(model.acte.Id, user.Id);
            ViewBag.IdActe = model.acte.Id;


            return PartialView(cliniques);
        }
        [HttpPost]
        public int GetLastIndexReserv()
        {
            return Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetLastIndexReserv() + 1;
        }
        public ActionResult EtatReservations()
        {
            return View();
        }
        [HttpPost]
        public ActionResult GetActesSpecialite(int specialiteId)
        {
            Actes Actes = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetActesSpecialite(specialiteId);
            List<Acte> Actesbis = new List<Acte>();
            Actesbis = Actes;
            return Json(Actesbis.ToArray(), JsonRequestBehavior.AllowGet);
        }
      
        public ActionResult FichePatient(int reservId, String datedebut, String datefin, String clinique, String ville)
        {
            Mutuelles mutuelles = new Mutuelles();
            mutuelles = Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.GetMutuelles();
            ViewBag.mutuelles = mutuelles;
            ViewBag.idreserv = reservId;
            ViewBag.datedebut = datedebut;
            ViewBag.datefin = datefin;
            ViewBag.clinique = clinique;
            ViewBag.ville = ville;
            return PartialView();
        }
        [HttpPost]
        public void SavePatient(MyViewModel model, string remarquesPatient, int idReserv)
        {
            Patient p = new Patient();
            p.Name = model.Patient.Name;
            p.Prenom = model.Patient.Prenom;
            p.Age = model.Patient.Age;
            p.CIN = model.Patient.CIN;
            p.Mutuelle= new Mutuelle() {Id= model.Mutuelle.Id};
            int idPatient =Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.AddPatient(p);
            Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.UpdateReservConfirmee(idReserv, idPatient, remarquesPatient);
            Reservation reserv = Kavaa.Modules.PortailMedical.Presentation.Services.Cabinet.GetInfoConvocation(idReserv);
            Service sw = new ServiceClient();
            //String[] str = { reserv.Clinique.Name, reserv.Id + "", reserv.Patient.Prenom + " " + reserv.Patient.Name, reserv.Patient.CIN, reserv.Acte.Name, reserv.DateDebut + "", reserv.DateFin + "", reserv.Medecin.Name + " " + reserv.Medecin.Prenom };

            String[] str = {reserv.Clinique.Name, reserv.Id + "", reserv.Patient.Prenom+" "+reserv.Patient.Name, reserv.Patient.CIN, reserv.Acte.Name, "27/04/2013 11:15","27/04/2013 13:15", reserv.Medecin.Name+" "+reserv.Medecin.Prenom };
            genererConvocationRequest attstring = new genererConvocationRequest(str);
            sw.genererConvocation(attstring);
            String[] str1 = { "NA 3456231", "27/05/2013", "Cabinet LAHLOU","CD 345678","53, Bd Abdelmoumen 12000", "0532698714","cab_lahlou@gmail.com" };
            genererContratRequest contrat = new genererContratRequest(str1);

            sw.genererContrat(contrat);



        }
        [HttpPost]
        public ActionResult ActiverCompte(int iduser)
        {

            Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.ActiverCompte(iduser);
            return RedirectToAction("ComptesCabinet");
        }

        [HttpPost]
        public ActionResult DesactiverCompte(int iduser)
        {

            Kavaa.Modules.PortailMedical.Presentation.Services.PortailMedical.DesactiverCompte(iduser);
            return RedirectToAction("ComptesCabinet");
        }
        public ActionResult Dashboard()
        {
            return PartialView();
        }
    }
}
